#!/bin/sh

set -xe
env

HOMEDIR=$(pwd)

function clean_up {
    set +e

    # Logs need to be in a specific place to be picked up.
    sudo mv ${HOMEDIR}/output/logs ${HOMEDIR}

    # Tear down the atomic host and image
    sudo docker run --privileged -it --link libvirtd:libvirtd -e commit=${commit} -e image2boot=${image2boot} -e state=absent -v /var/lib/libvirt/:/var/lib/libvirt/ -v ${HOMEDIR}/output/:/root/output/ -v ${HOMEDIR}/ci-pipeline/:/root/ci-pipeline ostree_boot_image

    # Kill our libvirtd docker instance.
    #  We can change this in the future to have it stick around if needed
    sudo docker kill libvirtd
    sudo docker rm libvirtd
}
trap clean_up EXIT SIGHUP SIGINT SIGTERM

if [ "${branch}" = "master" -o "${branch}" = "rawhide" ]; then
    branch="rawhide"
    VERSION="rawhide"
else
    VERSION=$(echo $branch | sed -e 's/[a-zA-Z]*//')
fi

# Make sure logs are empty so we don't report previous build
# if we fail
if [ -e "${HOMEDIR}/output/logs" ]; then
    sudo rm -rf ${HOMEDIR}/output/logs >/dev/null 2>&1
    echo "rm -rf ${HOMEDIR}/output/logs rc:$?"
fi
mkdir -p ${HOMEDIR}/output

pushd $HOMEDIR/ci-pipeline/config/Dockerfiles/rsync
sudo docker build -t rsync-container .
popd

pushd $HOMEDIR/ci-pipeline/config/Dockerfiles/libvirtd
sudo docker build --build-arg OSTREE_REPO_SERVER=artifacts.ci.centos.org -t libvirtd .
popd

pushd $HOMEDIR/ci-pipeline/config/Dockerfiles/ostree_boot_image
sudo docker build -t ostree_boot_image .
popd

sudo docker run --privileged --cap-add=SYS_ADMIN -v ${HOMEDIR}/output:/home/output -e rsync_paths="images" -e rsync_from="${RSYNC_USER}@${RSYNC_SERVER}::${RSYNC_DIR}/${branch}/" -e rsync_to="/home/output/" -e RSYNC_PASSWORD="$RSYNC_PASSWORD" rsync-container
echo $?

sudo docker run --privileged -d \
-v /var/lib/libvirt/:/var/lib/libvirt/ \
-v /sys/fs/cgroup:/sys/fs/cgroup:rw --name libvirtd libvirtd

sudo docker run --privileged -it --link libvirtd:libvirtd -e commit=${commit} -e image2boot=${image2boot} -e state=present -v /var/lib/libvirt/:/var/lib/libvirt/ -v ${HOMEDIR}/output/:/root/output/ -v ${HOMEDIR}/ci-pipeline/:/root/ci-pipeline ostree_boot_image
echo $?

# If image2boot is defined then symlink it as latest
if [ -n "$image2boot" ]; then
    pushd ${HOMEDIR}/output
    pushd images
    sudo ln -sf $(basename $image2boot) latest-atomic.qcow2
    popd
    # rsync the images directory back if we update the symlink
    for v in images; do
        rsync --delete --stats -a ${v}/ ${RSYNC_USER}@${RSYNC_SERVER}::${RSYNC_DIR}/${branch}/${v}/
    done
    popd
fi

